package utils

import (
	"b2c-delivery-optimization/internal/model"
	"fmt"
	"log"
	"time"

	"gorm.io/gorm"
)

// RunMigrations 运行数据库迁移
func RunMigrations() error {
	log.Println("开始数据库迁移...")

	// 创建表
	if err := DB.AutoMigrate(
		&model.Wave{},
		&model.WaveOrder{},
		&model.DeliveryStation{},
		&model.Vehicle{},
		&model.Order{},
		&model.OrderItem{},
		&model.PickingTask{},
		&model.PickingItem{},
		&model.Route{},
		&model.Stop{},
	); err != nil {
		return fmt.Errorf("数据库迁移失败: %v", err)
	}

	log.Println("数据库迁移完成")
	return nil
}

// SeedTestData 添加测试数据
func SeedTestData(db *gorm.DB) error {
	log.Println("开始添加测试数据...")

	// 禁用外键约束
	if err := db.Exec("SET FOREIGN_KEY_CHECKS = 0").Error; err != nil {
		return fmt.Errorf("禁用外键约束失败: %v", err)
	}

	// 清空所有表
	if err := db.Exec("TRUNCATE TABLE order_items").Error; err != nil {
		return fmt.Errorf("清空订单项表失败: %v", err)
	}
	if err := db.Exec("TRUNCATE TABLE stops").Error; err != nil {
		return fmt.Errorf("清空停靠点表失败: %v", err)
	}
	if err := db.Exec("TRUNCATE TABLE routes").Error; err != nil {
		return fmt.Errorf("清空路线表失败: %v", err)
	}
	if err := db.Exec("TRUNCATE TABLE orders").Error; err != nil {
		return fmt.Errorf("清空订单表失败: %v", err)
	}
	if err := db.Exec("TRUNCATE TABLE waves").Error; err != nil {
		return fmt.Errorf("清空波次表失败: %v", err)
	}
	if err := db.Exec("TRUNCATE TABLE wave_orders").Error; err != nil {
		return fmt.Errorf("清空波次订单关联表失败: %v", err)
	}
	if err := db.Exec("TRUNCATE TABLE vehicles").Error; err != nil {
		return fmt.Errorf("清空车辆表失败: %v", err)
	}
	if err := db.Exec("TRUNCATE TABLE delivery_stations").Error; err != nil {
		return fmt.Errorf("清空配送站表失败: %v", err)
	}

	// 启用外键约束
	if err := db.Exec("SET FOREIGN_KEY_CHECKS = 1").Error; err != nil {
		return fmt.Errorf("启用外键约束失败: %v", err)
	}

	// 添加配送站测试数据
	stations := []model.DeliveryStation{
		{
			ID:          "DS001",
			Name:        "江北配送站",
			Capacity:    1000,
			ServiceArea: 5.0,
		},
		{
			ID:          "DS002",
			Name:        "海曙配送站",
			Capacity:    1000,
			ServiceArea: 5.0,
		},
	}

	if err := db.Create(&stations).Error; err != nil {
		return fmt.Errorf("添加配送站测试数据失败: %v", err)
	}

	// 添加车辆测试数据
	vehicles := []model.Vehicle{
		{
			ID:                "V001",
			Type:              model.VehicleTypeLarge,
			Capacity:          1000,
			MaxVolume:         50,
			CurrentLoad:       0,
			CurrentVolume:     0,
			Status:            model.VehicleStatusAvailable,
			DeliveryStationID: "DS001",
		},
		{
			ID:                "V002",
			Type:              model.VehicleTypeSmall,
			Capacity:          500,
			MaxVolume:         20,
			CurrentLoad:       0,
			CurrentVolume:     0,
			Status:            model.VehicleStatusAvailable,
			DeliveryStationID: "DS002",
		},
	}

	if err := db.Create(&vehicles).Error; err != nil {
		return fmt.Errorf("添加车辆测试数据失败: %v", err)
	}

	// 添加订单测试数据
	orders := []model.Order{
		{
			ID:                "O001",
			CustomerID:        "C001",
			DeliveryStationID: "DS001",
			Status:            model.OrderStatusPending,
			Priority:          1,
			CreateTime:        time.Now(),
			ReleaseTime:       time.Now().Add(24 * time.Hour),
			Location: model.Location{
				Latitude:  30.123,
				Longitude: 120.123,
			},
			Items: []model.OrderItem{
				{
					ProductID: "P001",
					Quantity:  2,
					SKU:       "SKU001",
				},
			},
		},
		{
			ID:                "O002",
			CustomerID:        "C002",
			DeliveryStationID: "DS001",
			Status:            model.OrderStatusPending,
			Priority:          2,
			CreateTime:        time.Now(),
			ReleaseTime:       time.Now().Add(24 * time.Hour),
			Location: model.Location{
				Latitude:  30.124,
				Longitude: 120.124,
			},
			Items: []model.OrderItem{
				{
					ProductID: "P002",
					Quantity:  4,
					SKU:       "SKU002",
				},
			},
		},
		{
			ID:                "O003",
			CustomerID:        "C003",
			DeliveryStationID: "DS002",
			Status:            model.OrderStatusPending,
			Priority:          3,
			CreateTime:        time.Now(),
			ReleaseTime:       time.Now().Add(24 * time.Hour),
			Location: model.Location{
				Latitude:  30.125,
				Longitude: 120.125,
			},
			Items: []model.OrderItem{
				{
					ProductID: "P003",
					Quantity:  6,
					SKU:       "SKU003",
				},
			},
		},
	}

	if err := db.Create(&orders).Error; err != nil {
		return fmt.Errorf("添加订单测试数据失败: %v", err)
	}

	// 添加波次测试数据
	now := time.Now()
	wave := &model.Wave{
		ID:                "W001",
		DeliveryStationID: "DS001",
		Status:            model.WaveStatusCreated,
		StartTime:         now,
		EndTime:           now.Add(24 * time.Hour),
		CreatedAt:         now,
		UpdatedAt:         now,
	}

	if err := db.Create(wave).Error; err != nil {
		return fmt.Errorf("添加波次测试数据失败: %v", err)
	}

	// 添加波次订单关联测试数据
	waveOrders := []model.WaveOrder{
		{
			ID:        "WO001",
			WaveID:    "W001",
			OrderID:   "O001",
			CreatedAt: now,
			UpdatedAt: now,
		},
		{
			ID:        "WO002",
			WaveID:    "W001",
			OrderID:   "O002",
			CreatedAt: now,
			UpdatedAt: now,
		},
	}

	if err := db.Create(&waveOrders).Error; err != nil {
		return fmt.Errorf("添加波次订单关联测试数据失败: %v", err)
	}

	log.Println("测试数据添加完成")
	return nil
}
